#include "widget.h"
#include "ui_widget.h"
#include "parcel_dao.h"
#include <QPalette>
#include <QHeaderView>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->table = ui->tableWidget;

    QStringList headerLabels;
    headerLabels << "快递单号" << "物流编号" << "运单号码"
                 << "发件人" << "收件人" << "发件地址"
                 << "接收地址" << "当前地址" << "即将送往";
    table->setRowCount(0);
    table->setColumnCount(9);
    table->setHorizontalHeaderLabels(headerLabels);
    table->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
    table->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::onBarcodeScanned(const QString* barcode)
{
    if (barcode == NULL) {
        qCritical("Can't read barcode\n");
        return;
    }

    Parcel parcel;
    if (!parcelDao.findByBarcode(barcode, &parcel)) {
        qDebug("Can't find %s\n", barcode->toLatin1().data());

        QString msg = QString("未找到条目 %1.").arg(barcode->toLatin1().data());
        updateStatus(msg, false);
        return;
    }

    //parcelDao.out(barcode);
    updateTable(parcel);
}

void Widget::updateTable(const Parcel& parcel)
{
    int row = table->rowCount();
    table->insertRow(row);
    table->setItem(row, 0, new QTableWidgetItem(parcel.getExpressNum()));
    table->setItem(row, 1, new QTableWidgetItem(parcel.getLogisticsNum()));
    table->setItem(row, 2, new QTableWidgetItem(parcel.getBarcode()));
    table->setItem(row, 3, new QTableWidgetItem(parcel.getSender()));
    table->setItem(row, 4, new QTableWidgetItem(parcel.getRecipient()));
    table->setItem(row, 5, new QTableWidgetItem(parcel.getSendingAddr()));
    table->setItem(row, 6, new QTableWidgetItem(parcel.getRecivingAddr()));
    table->setItem(row, 7, new QTableWidgetItem(parcel.getCurrentAddr()));
    table->setItem(row, 8, new QTableWidgetItem(parcel.getNextAddr()));
    table->scrollToBottom();
}

void Widget::updateStatus(const QString& msg, bool flag)
{
    QString status("当前状态: ");
    status.append(msg);

    ui->label->clear();
    ui->label->setText(status);

    QPalette palette;
    if (flag) {
        palette.setColor(QPalette::WindowText, Qt::darkGreen);
    } else {
        palette.setColor(QPalette::WindowText, Qt::red);
    }
    ui->label->setPalette(palette);
}

void Widget::on_pushButton_clicked()
{
    emit quitThread();
    this->close();
}
